import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../style/style.dart';
import '../../widgets/my_app_bar.dart';
import 'security_scan_logic.dart';

/// 安全检测页面
class SecurityScanView extends StatefulWidget {
  const SecurityScanView({super.key});

  @override
  State<SecurityScanView> createState() => _SecurityScanViewState();
}

class _SecurityScanViewState extends State<SecurityScanView> with SingleTickerProviderStateMixin {
  final SecurityScanLogic logic = Get.put(SecurityScanLogic());
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.elasticOut),
    );
    
    // 监听检测完成状态，触发动画
    ever(logic.showResult, (showResult) {
      if (showResult) {
        _animationController.forward();
      }
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: const MyAppBar(
        title: '安全检测',
        isBack: true,
      ),
      body: Obx(() {
        if (logic.showResult.value) {
          return _buildResultPage();
        } else {
          return _buildScanningPage();
        }
      }),
    );
  }

  /// 构建检测中页面
  Widget _buildScanningPage() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(20.r),
      child: Column(
        children: [
          // 检测动画区域
          _buildScanAnimation(),
          SizedBox(height: 40.h),
          
          // 进度条
          _buildProgressBar(),
          SizedBox(height: 10.h),
          const MyAdFeedView(),
          SizedBox(height: 10.h),
          // 当前检测项目
          _buildCurrentScanItem(),
          SizedBox(height: 40.h),
          
          // 检测说明
          _buildScanDescription(),
        ],
      ),
    );
  }

  /// 构建检测动画
  Widget _buildScanAnimation() {
    return Container(
      height: 200.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 背景扫描线
          Positioned.fill(
            child: CustomPaint(
              painter: _ScanLinePainter(progress: logic.progress.value),
            ),
          ),
          
          // 中央图标
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.security,
                size: 60.r,
                color: kAppThemeColor,
              ),
              SizedBox(height: 10.h),
              Text(
                '安全检测中',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    return Column(
      children: [
        LinearProgressIndicator(
          value: logic.progress.value,
          backgroundColor: Colors.grey[300],
          valueColor: AlwaysStoppedAnimation<Color>(kAppThemeColor),
          minHeight: 8.h,
          borderRadius: BorderRadius.circular(4.r),
        ),
        SizedBox(height: 8.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '检测进度',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[600],
              ),
            ),
            Text(
              '${(logic.progress.value * 100).toStringAsFixed(0)}%',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
                color: kAppThemeColor,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建当前检测项目
  Widget _buildCurrentScanItem() {
    return Container(
      padding: EdgeInsets.all(16.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Icon(
            Icons.search,
            size: 24.r,
            color: kAppThemeColor,
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '当前检测项目',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[500],
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  logic.currentScanItem.value,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey[800],
                  ),
                ),
              ],
            ),
          ),
          Icon(
            Icons.autorenew,
            size: 20.r,
            color: Colors.grey[400],
          ),
        ],
      ),
    );
  }

  /// 构建检测说明
  Widget _buildScanDescription() {
    return Container(
      padding: EdgeInsets.all(16.r),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.info_outline,
                size: 20.r,
                color: Colors.blue[600],
              ),
              SizedBox(width: 8.w),
              Text(
                '检测说明',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue[600],
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Text(
            '安全检测正在全面检查您的设备安全状况，包括系统权限、应用安全、网络连接、数据加密等多个方面。检测过程可能需要几分钟时间，请耐心等待。',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.blue[700],
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建结果页面
  Widget _buildResultPage() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(20.r),
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Column(
          children: [
            // 结果卡片
            _buildResultCard(),
            SizedBox(height: 24.h),
            
            // 风险详情
            _buildRiskDetails(),
            SizedBox(height: 24.h),
            
            // 操作按钮
            _buildActionButtons(),
          ],
        ),
      ),
    );
  }

  /// 构建结果卡片
  Widget _buildResultCard() {
    final resultColor = logic.getResultColor();
    
    return Card(
      elevation: 4,
      child: Padding(
        padding: EdgeInsets.all(24.r),
        child: Column(
          children: [
            Container(
              width: 80.r,
              height: 80.r,
              decoration: BoxDecoration(
                color: resultColor.withOpacity(0.1),
                shape: BoxShape.circle,
                border: Border.all(color: resultColor, width: 2),
              ),
              child: Icon(
                _getResultIcon(),
                size: 40.r,
                color: resultColor,
              ),
            ),
            SizedBox(height: 16.h),
            Text(
              logic.scanResult.value,
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: resultColor,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              logic.resultDescription.value,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[600],
                height: 1.4,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.warning_amber,
                  size: 16.r,
                  color: resultColor,
                ),
                SizedBox(width: 4.w),
                Text(
                  '发现 ${logic.riskCount.value} 个风险',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: resultColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建风险详情
  Widget _buildRiskDetails() {
    final riskDetails = logic.getRiskDetails();
    
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16.r),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '详细报告',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 16.h),
            ...riskDetails.map((detail) => Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(
                    Icons.circle,
                    size: 8.r,
                    color: Colors.grey[500],
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: Text(
                      detail,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[700],
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            )).toList(),
          ],
        ),
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: OutlinedButton(
            onPressed: () => Get.back(),
            style: OutlinedButton.styleFrom(
              padding: EdgeInsets.symmetric(vertical: 12.h),
              side: BorderSide(color: kAppThemeColor),
            ),
            child: Text(
              '返回',
              style: TextStyle(
                fontSize: 16.sp,
                color: kAppThemeColor,
              ),
            ),
          ),
        ),
        SizedBox(width: 12.w),
        Expanded(
          child: ElevatedButton(
            onPressed: logic.rescan,
            style: ElevatedButton.styleFrom(
              backgroundColor: kAppThemeColor,
              padding: EdgeInsets.symmetric(vertical: 12.h),
            ),
            child: Text(
              '重新检测',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 获取结果图标
  IconData _getResultIcon() {
    switch (logic.scanResult.value) {
      case '安全':
        return Icons.check_circle;
      case '低风险':
        return Icons.warning_amber;
      case '有风险':
        return Icons.error_outline;
      default:
        return Icons.help_outline;
    }
  }
}

/// 扫描线绘制器
class _ScanLinePainter extends CustomPainter {
  final double progress;

  _ScanLinePainter({required this.progress});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue.withOpacity(0.1)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0;

    // 绘制扫描线
    final lineY = size.height * progress;
    canvas.drawLine(
      Offset(0, lineY),
      Offset(size.width, lineY),
      paint,
    );

    // 绘制扫描点
    final dotPaint = Paint()
      ..color = Colors.blue.withOpacity(0.3)
      ..style = PaintingStyle.fill;

    final dotX = (progress * size.width * 2) % size.width;
    canvas.drawCircle(Offset(dotX, lineY), 3, dotPaint);
  }

  @override
  bool shouldRepaint(covariant _ScanLinePainter oldDelegate) {
    return progress != oldDelegate.progress;
  }
}